package com.kws.merchant.service.impl;


import com.baomidou.mybatisplus.core.toolkit.ObjectUtils;
import com.kws.common.config.constant.MinioCommonBucket;
import com.kws.common.config.util.DateTimeUtil;
import com.kws.common.core.utils.StringUtils;
import com.kws.common.core.utils.uuid.UUID;
import com.kws.common.security.auth.AuthUtil;
import com.kws.merchant.config.MinioAPI;
import com.kws.merchant.domain.*;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.kws.merchant.domain.po.*;
import com.kws.merchant.domain.vo.WorkTickVo;
import com.kws.merchant.mapper.OperationTicketMapper;
import com.kws.merchant.service.*;
import com.kws.merchant.util.FileUtil;
import com.kws.merchant.util.PoiWordUtil;
import com.kws.system.api.RemoteUserService;
import com.kws.system.api.domain.SysUser;
import org.apache.ibatis.annotations.Case;
import org.apache.poi.ooxml.extractor.POIXMLTextExtractor;
import org.apache.poi.openxml4j.opc.OPCPackage;
import org.apache.poi.xwpf.extractor.XWPFWordExtractor;
import org.apache.poi.xwpf.usermodel.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;

import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.multipart.MultipartFile;

import java.io.*;
import java.net.URL;
import java.net.URLEncoder;
import java.nio.charset.StandardCharsets;
import java.rmi.MarshalledObject;
import java.text.SimpleDateFormat;
import java.time.LocalDate;
import java.util.*;
import java.util.stream.Collectors;

/**
 * 运维-两票管理(OperationTicket)表服务实现类
 *
 * @author yxy
 * @since 2024-10-28 08:54:06
 */
@Service("operationTicketService")
public class OperationTicketServiceImpl extends ServiceImpl<OperationTicketMapper, OperationTicket> implements OperationTicketService {

    @Resource
    private OperationTicketMapper operationTicketMapper;
    @Autowired
    private OperationTicketFileService operationTicketFileService;
    @Autowired
    private OperationTicketTaskService operationTicketTaskService;
    @Autowired
    private OperationTicketItemService operationTicketItemService;
    @Autowired
    private OperationTicketMemberService operationTicketMemberService;
    @Autowired
    private MinioAPI minioAPI;
    @Autowired
    private ItemService itemService;

    /**
     * 分页查询列表
     */
    @Override
    public Page<OperationTicket> pageList(TicketPo ticketPo) {
        Integer pageSize = ticketPo.getPageSize();
        Integer totalPage = ticketPo.getTotalPage();
        String ticketNo = ticketPo.getTicketNo();//票号
        String workType = ticketPo.getWorkType();//工作票类型
        String handleType = ticketPo.getHandleType();//操作票类型
        Integer status = ticketPo.getStatus();//状态0已处理 1未处理 2作废
        String type = ticketPo.getType();
        SysUser sysUser = AuthUtil.getLoginUser().getSysUser();
        String sql = " o.merchant_id=" + sysUser.getCompanyId();
        if (StringUtils.isNotEmpty(ticketNo)) {
            sql += " and o.ticket_no=" + ticketNo;
        }
        if (null != status) {
            sql += " and o.status=" + status;
        }
        int sizeNum = (pageSize - 1) * totalPage;//计算分页
        sql += " and o.type=" + type;
        if (StringUtils.isNotEmpty(type)) {

            if ("0".equals(type)) {
                if (StringUtils.isNotEmpty(workType)) {
                    sql += " and o.work_type=" + workType;
                }
            }
            if ("1".equals(type)) {
                if (StringUtils.isNotEmpty(handleType)) {
                    sql += " and o.handle_type=" + handleType;
                }
            }
            /*if ("2".equals(type)) {
                sql += " and o.status=" + 0;
            }*/
        }
        int total = operationTicketMapper.countToTal(sql);
        //查询数据
        List<OperationTicket> records = operationTicketMapper.getRecords(sql, sizeNum, totalPage);
        records.forEach(x -> {
            List<OperationTicketTask> taskList = operationTicketTaskService.listByTicketId(x.getId());
            List<OperationTicketItem> itemList = operationTicketItemService.listByTicketId(x.getId());
            List<OperationTicketMember> memberList = operationTicketMemberService.listByTicketId(x.getId());
            x.setTaskList(taskList);
            x.setItemList(itemList);
            x.setMemberList(memberList);
        });
        Page<OperationTicket> page = new Page<>();
        page.setRecords(records);
        page.setTotal(total);
        page.setCurrent(pageSize);
        page.setPages((total + totalPage - 1) / totalPage);
        page.setSize(totalPage);
        return page;
    }

    /**
     * 新增工作票
     *
     * @param workPo
     * @return
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public Object addWorkTicket(WorkPo workPo) {
        OperationTicket operationTicket = new OperationTicket();
        operationTicket.setTicketNo(UUID.randomUUID().toString());
        operationTicket.setWorkType(workPo.getWorkType());
        operationTicket.setWorkPrincipal(workPo.getWorkPrincipal());
        operationTicket.setWorkTime(workPo.getWorkTime());
        operationTicket.setSafetyPrecautions(workPo.getSafetyPrecautions());
        operationTicket.setType(0);
        operationTicket.setStatus(1);
        SysUser sysUser = AuthUtil.getLoginUser().getSysUser();
        operationTicket.setMerchantId(sysUser.getCompanyId());
        this.save(operationTicket);
        List<OperationTicketMember> workMembers = workPo.getWorkMembers();
        workMembers.forEach(x -> {
            x.setTicketId(operationTicket.getId());
        });
        List<OperationTicketTask> taskList = workPo.getTaskList();
        taskList.forEach(x -> {
            x.setTicketId(operationTicket.getId());
        });
        //任务地点
        operationTicketTaskService.saveBatch(taskList);
        operationTicketMemberService.saveBatch(workMembers);
        return true;
    }

    /**
     * 新增操作票
     *
     * @param handlePo
     * @return
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public Object addHandleTicket(HandlePo handlePo) {
        OperationTicket operationTicket = new OperationTicket();
        operationTicket.setTicketNo(UUID.randomUUID().toString());
        operationTicket.setHandleType(handlePo.getHandleType());
        operationTicket.setHandleTask(handlePo.getHandleTask());
        operationTicket.setHandleOperator(handlePo.getHandleOperator());
        operationTicket.setHandleGuardian(handlePo.getHandleGuardian());
        operationTicket.setWorkTime(handlePo.getWorkTime());
        operationTicket.setType(1);
        operationTicket.setStatus(1);
        SysUser sysUser = AuthUtil.getLoginUser().getSysUser();
        operationTicket.setMerchantId(sysUser.getCompanyId());
        this.save(operationTicket);
        List<OperationTicketItem> itemList = handlePo.getItemList();
        itemList.forEach(x -> {
            x.setTicketId(operationTicket.getId());
        });
        //项目
        operationTicketItemService.saveBatch(itemList);
        return true;
    }

    /**
     * 数据统计
     *
     * @param dept
     * @param startTime
     * @param endTime
     * @return
     */
    @Override
    public WorkTickVo statistics(String dept, String startTime, String endTime) {
        HashMap<String, String> map = new HashMap<>();
        map.put("workTicket", "100");//工作票
        map.put("cancellation", "3");//作废
        map.put("yield", "97%");//合格率
        WorkTickVo workTickVo = new WorkTickVo();
        return workTickVo;
    }

    /**
     * 通过主键查询单条数据
     *
     * @param id
     * @return
     */
    @Override
    public OperationTicket detailById(Long id) {
        OperationTicket operationTicket = operationTicketMapper.detailById(id);
        if (ObjectUtils.isEmpty(operationTicket)) {
            throw new RuntimeException("没有查询到该票信息");
        }
        operationTicket.setFile(FileUtil.fixFileName() + operationTicket.getFile());
        //查询票据任务
        List<OperationTicketTask> taskList = operationTicketTaskService.listByTicketId(id);
        //查询票据项目
        List<OperationTicketItem> itemList = operationTicketItemService.listByTicketId(id);
        //查询工作票成员
        List<OperationTicketMember> memberList = operationTicketMemberService.listByTicketId(id);
        operationTicket.setTaskList(taskList);
        operationTicket.setItemList(itemList);
        operationTicket.setMemberList(memberList);

        return operationTicket;
    }

    /**
     * 上传两票文件
     *
     * @return
     */
    @Override
    public Object uploadTickFile(TickFilePo tickFilePo) {
        SysUser sysUser = AuthUtil.getLoginUser().getSysUser();
        Long companyId = sysUser.getCompanyId();
        MultipartFile file = tickFilePo.getFile();
        Integer tickType = tickFilePo.getTickType();
        Integer type = tickFilePo.getType();
        try {
            InputStream in = file.getInputStream();
            XWPFDocument document = new XWPFDocument(in);
            WorkPo workPo = new WorkPo();
            HandlePo handlePo = new HandlePo();
            if (type == 0) {
                workPo.setWorkType(tickType);
                //工作票导入
                // 0电气带电作业 1电气第一种 2电气第二种 3紧急抢修工作票
                switch (tickType) {
                    case 0:
                        workPo = workType0(workPo, document, companyId);
                        break;
                    case 1:
                        workPo = workType1(workPo, document, companyId);
                        break;
                    case 2:
                        workPo = workType2(workPo, document, companyId);
                        break;
                    case 3:
                        workPo = workType3(workPo, document, companyId);
                        break;
                }
                //新增操作票
                this.addWorkTicket(workPo);
            } else {
                handlePo.setHandleType(tickType);
                //操作票导入
                handlePo = handleType0(handlePo, document, companyId);
                this.addHandleTicket(handlePo);
            }
            in.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
        return null;
    }

    private HandlePo handleType0(HandlePo handlePo, XWPFDocument document, Long companyId) {
        // 遍历文档中的所有元素（段落和表格）
        List<IBodyElement> bodyElements = document.getBodyElements();
        List<XWPFTable> tables = bodyElements.get(0).getBody().getTables();
        XWPFTable xwpfTable = tables.get(0);

        //操作开始时间
        String startTime = getRowSize(2, 0, xwpfTable).replaceAll("操作开始时间：", "").trim();
        String endTime = getRowSize(2, 1, xwpfTable).replaceAll("操作结束时间：", "").trim();
        //操作任务
        String handleTask = getRowSizeToIndex(4, 0, 0, 1, xwpfTable);
        //操作项目-项目
        String sort1 = getRowSize(6, 0, xwpfTable);
        String item1 = getRowSize(6, 1, xwpfTable);
        String sort2 = getRowSize(7, 0, xwpfTable);
        String item2 = getRowSize(7, 1, xwpfTable);
        String sort3 = getRowSize(8, 0, xwpfTable);
        String item3 = getRowSize(8, 1, xwpfTable);
        String sort4 = getRowSize(9, 0, xwpfTable);
        String item4 = getRowSize(9, 1, xwpfTable);

        //操作人
        String handleOperator = getRowSizeToIndex(11, 0, 0, 1, xwpfTable);
        //监护人
        String handleGuardian = getRowSizeToIndex(11, 0, 0, 3, xwpfTable);

        handleOperation(handlePo, startTime, endTime, handleTask, sort1, item1, sort2, item2, sort3, item3, sort4, item4, handleGuardian, handleOperator, companyId);
        return handlePo;
    }

    private void handleOperation(HandlePo handlePo, String startTime, String endTime, String handleTask, String sort1, String item1, String sort2, String item2, String sort3, String item3, String sort4, String item4, String handleGuardian, String handleOperator, Long companyId) {
        handlePo.setWorkTime(startTime + "-" + endTime);
        handlePo.setHandleTask(handleTask);
        ArrayList<OperationTicketItem> list = new ArrayList<>();
        if (StringUtils.isNotEmpty(sort1) && StringUtils.isNotEmpty(item1)) {
            OperationTicketItem ticketItem = new OperationTicketItem();
            ticketItem.setSort(sort1);
            //查询当前商家是否存在当前项目
            Item item = itemService.getByMerchantName(item1);
            if (ObjectUtils.isEmpty(item)) {
                throw new RuntimeException("文件中的项目：" + item1 + "不存在系统中");
            }
            ticketItem.setItemId(item.getId());
            list.add(ticketItem);
        }
        if (StringUtils.isNotEmpty(sort2) && StringUtils.isNotEmpty(item2)) {
            OperationTicketItem ticketItem = new OperationTicketItem();
            ticketItem.setSort(sort2);
            //查询当前商家是否存在当前项目
            Item item = itemService.getByMerchantName(item2);
            if (ObjectUtils.isEmpty(item)) {
                throw new RuntimeException("文件中的项目：" + item2 + "不存在系统中");
            }
            ticketItem.setItemId(item.getId());
            list.add(ticketItem);
        }
        if (StringUtils.isNotEmpty(sort3) && StringUtils.isNotEmpty(item3)) {
            OperationTicketItem ticketItem = new OperationTicketItem();
            ticketItem.setSort(sort3);
            //查询当前商家是否存在当前项目
            Item item = itemService.getByMerchantName(item3);
            if (ObjectUtils.isEmpty(item)) {
                throw new RuntimeException("文件中的项目：" + item3 + "不存在系统中");
            }
            ticketItem.setItemId(item.getId());
            list.add(ticketItem);
        }
        if (StringUtils.isNotEmpty(sort4) && StringUtils.isNotEmpty(item4)) {
            OperationTicketItem ticketItem = new OperationTicketItem();
            ticketItem.setSort(sort4);
            //查询当前商家是否存在当前项目
            Item item = itemService.getByMerchantName(item4);
            if (ObjectUtils.isEmpty(item)) {
                throw new RuntimeException("文件中的项目：" + item4 + "不存在系统中");
            }
            ticketItem.setItemId(item.getId());
            list.add(ticketItem);
        }
        SysUser sysUser = null;
        if (StringUtils.isNotEmpty(handleGuardian)) {
            sysUser = operationTicketMapper.detailByNickName(handleGuardian, companyId);
        }
        if (ObjectUtils.isEmpty(sysUser)) {
            throw new RuntimeException("该商家没有查询到监护人信息:" + handleGuardian);
        }
        SysUser sysUser1 = null;
        if (StringUtils.isNotEmpty(handleOperator)) {
            sysUser1 = operationTicketMapper.detailByNickName(handleOperator, companyId);
        }
        if (ObjectUtils.isEmpty(sysUser1)) {
            throw new RuntimeException("该商家没有查询到操作人信息:" + handleOperator);
        }
        handlePo.setHandleGuardian(sysUser.getUserId());//监护人
        handlePo.setHandleOperator(sysUser1.getUserId());//操作人
        handlePo.setItemList(list);
    }

    /**
     * 工作票0表格分析
     *
     * @param document
     * @return
     */
    private WorkPo workType0(WorkPo workPo, XWPFDocument document, Long companyId) {
        // 遍历文档中的所有元素（段落和表格）
        List<IBodyElement> bodyElements = document.getBodyElements();
        List<XWPFTable> tables = bodyElements.get(0).getBody().getTables();
        XWPFTable xwpfTable = tables.get(0);

        //工作负责人
        String workPrincipal = getRowSizeToIndex(1, 0, 0, 1, xwpfTable);

        //工作班成员
        String workMember = getRowSizeToIndex(2, 0, 0, 1, xwpfTable);
        //工作地点-任务
        String workTask1 = getRowSize(5, 1, xwpfTable);
        String workSite1 = getRowSize(5, 2, xwpfTable);

        String workTask2 = getRowSize(6, 1, xwpfTable);
        String workSite2 = getRowSize(6, 2, xwpfTable);

        String workTask3 = getRowSize(7, 1, xwpfTable);
        String workSite3 = getRowSize(7, 2, xwpfTable);

        String workTask4 = getRowSize(8, 1, xwpfTable);
        String workSite4 = getRowSize(8, 2, xwpfTable);
        //计划工作时间
        String workTime = getRowSize(9, 0, xwpfTable).replaceAll("计划工作时间：", "").trim();
        //安全措施
        String safetyPrecautions = getRowSizeToIndex(11, 0, 0, 1, xwpfTable);
        extracted(workPo, workPrincipal, workMember, workTask1, workSite1, workTask2, workSite2, workTask3, workSite3, workTask4, workTime, workSite4, safetyPrecautions, companyId);
        return workPo;
    }

    private WorkPo workType1(WorkPo workPo, XWPFDocument document, Long companyId) {
        // 遍历文档中的所有元素（段落和表格）
        List<IBodyElement> bodyElements = document.getBodyElements();
        List<XWPFTable> tables = bodyElements.get(0).getBody().getTables();
        XWPFTable xwpfTable = tables.get(0);

        //工作负责人
        String workPrincipal = getRowSizeToIndex(1, 0, 0, 1, xwpfTable);
        //工作班成员
        String workMember = getRowSizeToIndex(2, 0, 0, 1, xwpfTable);
        //工作地点-任务
        String workTask1 = getRowSize(5, 1, xwpfTable);
        String workSite1 = getRowSize(5, 2, xwpfTable);

        String workTask2 = getRowSize(6, 1, xwpfTable);
        String workSite2 = getRowSize(6, 2, xwpfTable);

        String workTask3 = getRowSize(7, 1, xwpfTable);
        String workSite3 = getRowSize(7, 2, xwpfTable);

        String workTask4 = getRowSize(8, 1, xwpfTable);
        String workSite4 = getRowSize(8, 2, xwpfTable);
        //计划工作时间
        String workTime = getRowSize(9, 0, xwpfTable).trim();
        //安全措施 todo 电气第一种票变化过大，后续加
//        String safetyPrecautions =  getRowSizeToIndex(11,0,0,1,xwpfTable);
        String safetyPrecautions = "";
        extracted(workPo, workPrincipal, workMember, workTask1, workSite1, workTask2, workSite2, workTask3, workSite3, workTask4, workTime, workSite4, safetyPrecautions, companyId);

        return workPo;
    }

    private WorkPo workType2(WorkPo workPo, XWPFDocument document, Long companyId) {
        // 遍历文档中的所有元素（段落和表格）
        List<IBodyElement> bodyElements = document.getBodyElements();
        List<XWPFTable> tables = bodyElements.get(0).getBody().getTables();
        XWPFTable xwpfTable = tables.get(0);

        //工作负责人
        String workPrincipal = getRowSizeToIndex(1, 0, 0, 1, xwpfTable);
        //工作班成员
        String workMember = getRowSizeToIndex(2, 0, 0, 1, xwpfTable);
        //工作地点-任务
        String workTask1 = getRowSize(5, 1, xwpfTable);
        String workSite1 = getRowSize(5, 2, xwpfTable);

        String workTask2 = getRowSize(6, 1, xwpfTable);
        String workSite2 = getRowSize(6, 2, xwpfTable);

        String workTask3 = getRowSize(7, 1, xwpfTable);
        String workSite3 = getRowSize(7, 2, xwpfTable);

        String workTask4 = getRowSize(8, 1, xwpfTable);
        String workSite4 = getRowSize(8, 2, xwpfTable);
        //计划工作时间
        String workTime = getRowSize(9, 0, xwpfTable).trim();
        String safetyPrecautions = getRowSizeToIndex(11, 0, 0, 1, xwpfTable);
        extracted(workPo, workPrincipal, workMember, workTask1, workSite1, workTask2, workSite2, workTask3, workSite3, workTask4, workTime, workSite4, safetyPrecautions, companyId);

        return workPo;
    }

    private WorkPo workType3(WorkPo workPo, XWPFDocument document, Long companyId) {
        // 遍历文档中的所有元素（段落和表格）
        List<IBodyElement> bodyElements = document.getBodyElements();
        List<XWPFTable> tables = bodyElements.get(0).getBody().getTables();
        XWPFTable xwpfTable = tables.get(0);

        //工作负责人
        String workPrincipal = getRowSizeToIndex(1, 0, 0, 1, xwpfTable);
        //工作班成员
        String workMember = getRowSizeToIndex(2, 0, 0, 1, xwpfTable);
        //工作地点-任务 todo 抢修操作票变化过大，后续增加
//        String workTask1 =  getRowSize(5,1,xwpfTable);
//        String workSite1 =  getRowSize(5,2,xwpfTable);
        String workTask1 = "";
        String workSite1 = "";

        String safetyPrecautions = getRowSizeToIndex(4, 0, 0, 1, xwpfTable);
        extracted2(workPo, workPrincipal, workMember, workTask1, workSite1, safetyPrecautions, companyId);

        return workPo;
    }


    private void extracted(WorkPo workPo, String workPrincipal, String workMember, String workTask1, String workSite1, String workTask2, String workSite2, String workTask3, String workSite3, String workTask4, String workSite4, String workTime, String safetyPrecautions, Long companyId) {
        ArrayList<OperationTicketTask> taskList = new ArrayList<>();
        if (StringUtils.isNotEmpty(workTask1) && StringUtils.isNotEmpty(workSite1)) {
            OperationTicketTask ticketTask = new OperationTicketTask();
            ticketTask.setTicketTask(workTask1);
            ticketTask.setTicketSite(workSite1);
            taskList.add(ticketTask);
        }
        if (StringUtils.isNotEmpty(workTask2) && StringUtils.isNotEmpty(workSite2)) {
            OperationTicketTask ticketTask = new OperationTicketTask();
            ticketTask.setTicketTask(workTask2);
            ticketTask.setTicketSite(workSite2);
            taskList.add(ticketTask);
        }
        if (StringUtils.isNotEmpty(workTask3) && StringUtils.isNotEmpty(workSite3)) {
            OperationTicketTask ticketTask = new OperationTicketTask();
            ticketTask.setTicketTask(workTask3);
            ticketTask.setTicketSite(workSite3);
            taskList.add(ticketTask);
        }
        if (StringUtils.isNotEmpty(workTask4) && StringUtils.isNotEmpty(workSite4)) {
            OperationTicketTask ticketTask = new OperationTicketTask();
            ticketTask.setTicketTask(workTask4);
            ticketTask.setTicketSite(workSite4);
            taskList.add(ticketTask);
        }
        SysUser sysUser = null;
        if (StringUtils.isNotEmpty(workPrincipal)) {
            sysUser = operationTicketMapper.detailByNickName(workPrincipal, companyId);
        }
        if (ObjectUtils.isEmpty(sysUser)) {
            throw new RuntimeException("该商家没有查询到负责人信息:" + workPrincipal);
        }
        ArrayList<OperationTicketMember> operationTicketMembers = new ArrayList<>();
        if (StringUtils.isNotEmpty(workMember)) {
            String[] split = workMember.split(",|，");
            Arrays.stream(split).forEach(x -> {
                OperationTicketMember operationTicketMember = new OperationTicketMember();
                SysUser user = operationTicketMapper.detailByNickName(x, companyId);
                if (ObjectUtils.isEmpty(user)) {
                    throw new RuntimeException("该商家没有查询到该成员：" + x);
                }
                operationTicketMember.setUserId(user.getUserId());
                operationTicketMembers.add(operationTicketMember);

            });

        }
        workPo.setWorkPrincipal(sysUser.getUserId());
        workPo.setWorkMembers(operationTicketMembers);
        workPo.setWorkTime(workTime);
        workPo.setSafetyPrecautions(safetyPrecautions);
        workPo.setTaskList(taskList);
    }

    private void extracted2(WorkPo workPo, String workPrincipal, String workMember, String workTask1, String workSite1, String safetyPrecautions, Long companyId) {
        ArrayList<OperationTicketTask> taskList = new ArrayList<>();
        if (StringUtils.isNotEmpty(workTask1) && StringUtils.isNotEmpty(workSite1)) {
            OperationTicketTask ticketTask = new OperationTicketTask();
            ticketTask.setTicketTask(workTask1);
            ticketTask.setTicketSite(workSite1);
            taskList.add(ticketTask);
        }
        ArrayList<OperationTicketMember> operationTicketMembers = new ArrayList<>();
        if (StringUtils.isNotEmpty(workMember)) {
            String[] split = workMember.split(",|，");
            Arrays.stream(split).forEach(x -> {
                OperationTicketMember operationTicketMember = new OperationTicketMember();
                SysUser user = operationTicketMapper.detailByNickName(workPrincipal, companyId);
                if (ObjectUtils.isEmpty(user)) {
                    throw new RuntimeException("该商家没有查询到该成员：" + x);
                }
                operationTicketMember.setUserId(user.getUserId());
                operationTicketMembers.add(operationTicketMember);

            });
        }
        SysUser sysUser = null;
        if (StringUtils.isNotEmpty(workPrincipal)) {
            sysUser = operationTicketMapper.detailByNickName(workPrincipal, companyId);
        }
        if (ObjectUtils.isEmpty(sysUser)) {
            throw new RuntimeException("没有查询到负责人信息:" + workPrincipal);
        }
        workPo.setWorkMembers(operationTicketMembers);
        workPo.setSafetyPrecautions(safetyPrecautions);
        workPo.setTaskList(taskList);
        workPo.setWorkPrincipal(sysUser.getUserId());
    }

    public String getRowSizeToIndex(int rowNum, int cellNum, int paragNum, int runNum, XWPFTable xwpfTable) {
        return xwpfTable.getRow(rowNum).getTableCells().get(cellNum).getBodyElements().get(0).getBody().getParagraphs().get(paragNum).getRuns().get(runNum).text();
    }

    public String getRowSize(int row, int size, XWPFTable xwpfTable) {
        return xwpfTable.getRow(row).getTableCells().get(size).getText();
    }

    /**
     * 下载两票文件
     *
     * @param id
     * @return
     */
    @Override
    public Object downloadTickFile(Long id, HttpServletResponse response) {
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd_HH_mm_ss");
        OperationTicket operationTicket = this.detailById(id);
        if (ObjectUtils.isEmpty(operationTicket)) {
            throw new RuntimeException("没有找到两票数据");
        }
        //如果已处理的话下载已处理的文件
        if (operationTicket.getStatus() == 0) {
            try {
                InputStream fis = minioAPI.download(MinioCommonBucket.HUATAI_PUB_BUCKET, operationTicket.getFile());
                XWPFDocument document = new XWPFDocument(fis);
                String fileName = sdf.format(new Date());
                response.setHeader("Content-disposition", "attachment;filename=" + URLEncoder.encode(fileName, "UTF-8"));
                ServletOutputStream fos = response.getOutputStream();
                document.write(fos);
            } catch (Exception e) {
                e.printStackTrace();
            }
            return true;

        }
        //获取票类型 类型0工作票 1操作票
        Integer type = operationTicket.getType();
        //工作票类型 工作票类型0电气带电作业 1电气第一种 2电气第二种 3紧急抢修工作票
        Integer workType = operationTicket.getWorkType();
        //操作票类型 操作票类型0倒闸 1检修 2特殊 3临时 4紧急
        Integer handleType = operationTicket.getHandleType();
        LambdaQueryWrapper<OperationTicketFile> wrapper = Wrappers.<OperationTicketFile>lambdaQuery().eq(OperationTicketFile::getType, type);
        if (type == 0) {
            //工作票
            wrapper.eq(OperationTicketFile::getWorkType, workType);
        } else {
            //操作票
            wrapper.eq(OperationTicketFile::getHandleType, handleType);
        }
        List<OperationTicketTask> taskList = operationTicket.getTaskList();
        List<OperationTicketItem> itemList = operationTicket.getItemList();
        List<OperationTicketMember> memberList = operationTicket.getMemberList();
        String collect = memberList.stream().map(x -> x.getUserName()).collect(Collectors.joining(","));
        //获取文件模板
        OperationTicketFile ticketFile = operationTicketFileService.getOne(wrapper);
        String[] split = ticketFile.getName().split("\\.");
        HashMap<String, String> map = new HashMap<>();
        if (type == 0) {
            map.put("workPrincipal", operationTicket.getWorkPrincipalName());//监护人
            map.put("workMember", collect);//工作班成员
            map.put("safetyPrecautions", operationTicket.getSafetyPrecautions());//安全措施
            map.put("workTime", operationTicket.getWorkTime());//计划工作时间
            map.put("task1", "");
            map.put("site1", "");
            map.put("task2", "");
            map.put("site2", "");
            map.put("task3", "");
            map.put("site3", "");
            map.put("task4", "");
            map.put("site4", "");
            int num = 1;
            //存储任务
            for (OperationTicketTask operationTicketTask : taskList) {
                String ticketTask = operationTicketTask.getTicketTask();
                String ticketSite = operationTicketTask.getTicketSite();
                map.put("task" + num, ticketTask);
                map.put("site" + num, ticketSite);
                num += 1;
            }
        } else {
            String workTime = operationTicket.getWorkTime();
            map.put("startTime", "");
            map.put("endTime", "");
            if (StringUtils.isNotEmpty(workTime)) {
                String[] split1 = workTime.split("-");
                map.put("startTime", split1[0]);
                map.put("endTime", split1[1]);
            }
            map.put("handleTask", operationTicket.getHandleTask());
            map.put("sort1", "");
            map.put("item1", "");
            map.put("sort2", "");
            map.put("item2", "");
            map.put("sort3", "");
            map.put("item3", "");
            map.put("sort4", "");
            map.put("item4", "");
            map.put("handle_operator", operationTicket.getHandleOperatorName());
            map.put("handle_guardian", operationTicket.getHandleGuardianName());
            int num = 1;
            //存储任务
            for (OperationTicketItem operationTicketItem : itemList) {
                String sort = operationTicketItem.getSort();
                String item = operationTicketItem.getItemName();
                map.put("sort" + num, sort);
                map.put("item" + num, item);
                num += 1;
            }
        }

        try {
            InputStream fis = minioAPI.download(MinioCommonBucket.HUATAI_PUB_BUCKET, ticketFile.getFile());
            XWPFDocument document = new XWPFDocument(fis);
            PoiWordUtil.replaceWord(document, map);
            String fileName = sdf.format(new Date()) + split[0] + ".docx";
            response.setHeader("Content-disposition", "attachment;filename=" + URLEncoder.encode(fileName, "UTF-8"));
            ServletOutputStream fos = response.getOutputStream();
            document.write(fos);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return true;
    }

    /**
     * 操作-上传文件-改变状态为已处理
     *
     * @param tickFilePo
     * @return
     */
    @Override
    public Object uploadFile(TicketStatus tickFilePo) {
        Long id = tickFilePo.getId();
        OperationTicket ticket = this.getById(id);
        if (ObjectUtils.isEmpty(ticket)) {
            throw new RuntimeException("没有改两票信息");
        }
        Integer status = ticket.getStatus();
        if (status != 1) {
            throw new RuntimeException("当前两票状态不可处理");
        }
        String filePath = tickFilePo.getFilePath();
        if (StringUtils.isEmpty(filePath)) {
            throw new RuntimeException("文件不能为空");
        }
        ticket.setFile(FileUtil.subFileName(filePath));
        ticket.setStatus(0);
        return this.updateById(ticket);
    }

    /**
     * 根据两票id作废两票
     *
     * @param id
     * @return
     */
    @Override
    public Object cancellation(Long id) {
        OperationTicket ticket = this.getById(id);
        if (ObjectUtils.isEmpty(ticket)) {
            throw new RuntimeException("没有改两票信息");
        }
        ticket.setStatus(2);
        return this.updateById(ticket);
    }

    public static void parseFile(InputStream in) {
        try {
            XWPFDocument document = new XWPFDocument(in);

            // 遍历文档中的所有元素（段落和表格）
            List<IBodyElement> bodyElements = document.getBodyElements();
            for (IBodyElement bodyElement : bodyElements) {
                if (bodyElement instanceof XWPFParagraph) {
                    XWPFParagraph paragraph = (XWPFParagraph) bodyElement;
                    System.out.println(paragraph.getStyleID() + ":" + paragraph.getText());
                } else if (bodyElement instanceof XWPFTable) {
                    System.out.println(((XWPFTable) bodyElement).getText());
                } else if (bodyElement instanceof XWPFPicture) {
                    System.out.println(Arrays.toString(((XWPFPicture) bodyElement).getPictureData().getData()));
                }
            }

            in.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}
